<template>
  <div class="article-page">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片盒子 -->
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{total}}条记录</span>
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            @click="open('add')"
            round>
            添加面经
          </el-button>
            </div>
          </template>
        <!-- 列表 -->
          <el-table
            :data="list"
            style="width: 100%">
            <el-table-column
              prop="stem"
              label="标题"
              width="400">
            </el-table-column>
            <el-table-column
              prop="creator"
              label="作者"
              width="180">
            </el-table-column>
             <el-table-column
              prop="likeCount"
              label="点赞"
              width="180">
            </el-table-column>
            <el-table-column
              prop="views"
              label="浏览数">
            </el-table-column>
            <el-table-column
              prop="createdAt"
              label="更新时间">
            </el-table-column>

              <el-table-column
              label="操作"
              width="120px">
               <template #default="{row}">
                 <div class="actions">
              <i class="el-icon-view" @click="open('preview',row.id)"></i>
              <i class="el-icon-edit-outline" @click="open('edit',row.id)"></i>
              <i class="el-icon-delete" @click=del(row.id)></i>
              </div>
               </template>
            </el-table-column>

          </el-table>
          <!-- 分页器
           @size-change监听每页条数的变化
           @current-change监听当前页的变化
           :page-size设置当前生效的 [每页条数]
           :current-page设置当前生效的[当前页]
           :total  设置[总条数]
           background 按钮底色
           -->
           <el-pagination
           background
           @current-change="fCurrentChange"
           :current-page="current"
           :page-size="pageSize"
           layout="prev, pager, next"
           :total="total"
           >
           </el-pagination>
      </el-card>
      <!-- 抽屉 -->
      <!-- :before-close="hClose" 关闭前的回调函数 -->
             <el-drawer
               :title="title[type]"
               :visible.sync="isShow"
               direction="rtl"
               :before-close="hClose"
               size="60%">
               <!-- 如果类型是预览 -->
               <div class="article-preview" v-if="type==='preview'">
                <h5>{{ form.stem }}</h5>
                <div v-html="form.content"></div>
               </div>

           <!-- 表单 -->
    <!--
       表单校验三步骤:
            1. el-form:model(数据对象) rules(规则对象)
            2. el-form-item :prop(规则名称)
            3. el-input:v-model(双向数据绑定)
            -->
           <el-form v-else ref="form" :model="form" :rules="rules" label-width="80px">
           <el-form-item label="标题" prop="stem">
             <el-input v-model="form.stem" placeholder="输入面经标题"></el-input>
           </el-form-item>
            <el-form-item label="内容" prop="content">
              <!-- 非element的组件都无法直接校验,需要手动在失去焦点时调用form.validateField方法进行校验 -->
              <!-- content:就是字段名 -->
               <quill-editor v-model="form.content" @blur="$refs.form.validateField('content')"></quill-editor>
           </el-form-item>
           <el-form-item>
           <el-button type="primary" @click="sumbit">确认</el-button>
           <el-button>取消</el-button>
         </el-form-item>
           </el-form>
      </el-drawer>
           </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { addArticle, delArticle, getArticle, getArticleList, updateArticle } from '@/api/article'
export default {
  name: 'article-page',
  components: {
    quillEditor
  },
  data () {
    return {
      list: [],
      current: 1,
      pageSize: 10,
      total: 0,
      isShow: false,
      type: 'add', // 抽屉的状态,取值范围add,preview,edit
      title: {
        add: '添加面经',
        preview: '预览面经',
        edit: '修改面经'
      },
      rules: {
        stem: [
          { required: true, message: '请输入标题', trigger: ['change', 'blur'] }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: ['change', 'blur'] }
        ]
      },
      form: {
        stem: '',
        content: ''
      }
    }
  },
  created () {
    this.initData()
  },
  methods: {
    // 因为后期添加删除都要重新渲染列表 所以建议封装函数
    async initData () {
      const res = await getArticleList({
        current: this.current,
        pageSize: this.pageSize
      })
      // console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    async del (id) {
      // console.log(id)
      // 发送请求
      await delArticle(id)
      // 提示用户删除成功
      this.$message.success('删除成功')
      // 渲染之前先判断,如果当前只有一条数据了,让current--
      // 额外加一个条件,必须得this.current大于1才能有空间
      if (this.list.length === 1 || this.current > 1) {
        this.current--
      }
      // 重新渲染
      this.initData()
    },
    fCurrentChange (val) {
      this.current = val
      this.initData()
    },
    // 抽屉函数
    async open (type, id) {
      // console.log(type, id)
      // 显示抽屉
      this.isShow = true
      // 除了添加面经外,其余两种情况都需要获取面经详情
      this.type = type
      // 判断打开的类型 来区别要不要发请求
      if (type !== 'add') {
        const res = await getArticle(id)
        // console.log(res)// data
        // 将请求成功的数据全部回显给表单 展开运算符
        this.form = { ...res.data }
      }
    },
    hClose (done) {
      // done是一个函数,调用可以关闭抽屉
      // 不用done也可以,this.isShow也可以
      this.$confirm('确认关闭？')
        .then(res => {
          // 当用户点击确定, .then的代码就会执行
          // 当用户点击取消,.catch的代码就会执行
          // done()
          this.closeDrawer()
        })
        .catch(e => {
          console.log('用户点击了取消', e)
        })
    },
    // 确认
    async sumbit () {
      // 1.校验
      await this.$refs.form.validate()
      // 判断当前是编辑还是添加
      if (this.type === 'add') {
        // 2.发请求
        await addArticle(this.form)
        // 3.提示用户
        this.$message.success('添加成功')
        // 回到第一页
        this.current = 1
      }

      if (this.type === 'edit') {
        // 发更新数据请求
        // 解构发请求需要的三个参数
        const { id, stem, content } = this.form
        await updateArticle({
          id, stem, content
        })
        this.$message.success('修改成功')
      }
      // 4.关闭抽屉
      this.closeDrawer()
      // 5.重新渲染
      // 回到第一页
      this.current = 1
      this.initData()
    },
    closeDrawer () {
      // 4.关闭抽屉
      this.isShow = false
      // 重置表单
      // 逻辑与  如果有表单,则resetFields()
      this.$refs.form && this.$refs.form.resetFields()

      // form数据对象也重置一下
      this.form = {
        stem: '',
        content: ''
      }
    }
  }
  // computed: {
  //   title () {
  //     let title = ''
  //     if (this.type === 'add') title = '添加面经'
  //   }
  // }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
